package com.shop.util;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;

import com.shop.bean.Goods;

/** 
 * @className: ShopingCart.java
 * @classDescription: 
 * @function: 
 * @author: Wentasy
 * @createTime: 2012-11-9 下午05:02:25
 * @modifyTime: 
 * @modifyReason: 
 * @since: JDK 1.6
 */
public class ShopingCart {
	private Connection conn = null;
	private PreparedStatement pstmt = null;
	private ResultSet rs = null;
	private float allPrice=0.0f;
	HashMap<String,String> hm=new HashMap<String,String>();//定义一个HashMap集合，用于存放书的id和类型
	
	
	/**
	 * 根据id返回货物的数量
	 * @param goodsId
	 * @return 货物的数量
	 */
	public String getGoodsNumById(String goodsId){
		return (String)hm.get(goodsId);
		
	}
	
	//添加货物
	public void addGoods(String goodsId,String goodsNum){
		hm.put(goodsId, goodsNum);
	}
	
	//删除货物
	public void delGoods(String goodsId){
		hm.remove(goodsId);
	}
	
	//清空货物
	public void clear(){
		hm.clear();
	}
	
	//修改货物数量
	public void updateGoods(String goodsId,String newNum){
		hm.put(goodsId, newNum);
	}
	
	//显示购物车
	public ArrayList<Goods> showShoppingCart(){
		ArrayList<Goods> al = new ArrayList<Goods>();
		
		try {
			String sql="select * from goods where goodsId in ";
			Iterator<String> it=hm.keySet().iterator();
			String temp="(";
			while(it.hasNext()){
				String goodsId=(String)it.next();
				if(it.hasNext()){
					temp += goodsId + ",";
				}else{
					temp += goodsId + ")";
				}
			}
			sql += temp;
			
			conn = ConnDB.getConn();
			pstmt = conn.prepareStatement(sql);
			rs = pstmt.executeQuery();
			
			while(rs.next()){
				Goods goods = new Goods();
				goods.setGoodsId(rs.getLong("goodsId"));
				goods.setGoodsName(rs.getString("goodsName"));
				goods.setGoodsIntro(rs.getString("goodsIntro"));
				goods.setGoodsPrice(rs.getFloat("goodsPrice"));
				goods.setGoodsNum(rs.getInt("goodsNum"));
				goods.setProducer(rs.getString("producer"));
				goods.setGoodsParId(rs.getLong("goodsParId"));
				goods.setImage(rs.getString("image"));
				
				al.add(goods);
				
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			try {
				ConnDB.close(rs);
				ConnDB.close(pstmt);
				ConnDB.close(conn);
			} catch (SQLException e) {
				e.printStackTrace();
			}
			
		}
		return al;
	}
	public float getAllPrice() {
		return allPrice;
	}
	public void setAllPrice(float allPrice) {
		this.allPrice = allPrice;
	}
	
	
}
